package com.gperp.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gperp.common.GPResult;
import com.gperp.mapper.AsAccountMapper;
import com.gperp.mapper.AsAccountdetailMapper;
import com.gperp.pojo.AsAccount;
import com.gperp.pojo.AsAccountExample;
import com.gperp.pojo.AsAccountdetail;
import com.gperp.pojo.AsAccountdetailExample;
import com.gperp.service.AccountDetailService;

@Service
public class AccountDetailServiceImpl implements AccountDetailService{
	@Resource
	private AsAccountdetailMapper asAccountdetailMapper;
	@Resource
	private AsAccountMapper asAccountMapper;
	@Override
	public Map<String, Object> queryList(Integer pageNo, Long userid) {
		Map<String,Object> map = new HashMap<String,Object>();
		PageHelper.startPage(pageNo, 8);
		AsAccountdetailExample example = new AsAccountdetailExample();
		example.createCriteria().andUseridEqualTo(userid);
		example.setOrderByClause("detaildatetime desc");
		PageInfo<AsAccountdetail> pageInfo = new PageInfo<AsAccountdetail>(asAccountdetailMapper.selectByExample(example));
		map.put("pageTotal", pageInfo.getTotal());
		map.put("pageList", pageInfo.getList());
		return map;
	}

	@Override
	public GPResult saveAccount(AsAccountdetail account) {
		try {
			//操作账号金额
			AsAccountExample example = new AsAccountExample();
			example.createCriteria().andUseridEqualTo(account.getUserid());
			List<AsAccount> userAccount = asAccountMapper.selectByExample(example);
			AsAccount asAccount = userAccount.get(0);
			if((asAccount.getMoney()+account.getMoney())>0){		//余额够就修改余额
				asAccount.setMoney(asAccount.getMoney()+account.getMoney());
				asAccountMapper.updateByPrimaryKeySelective(asAccount);
			}else{
				return GPResult.build(200, "NO","该账号余额不足");
			}
			//补全信息并添加信息
			account.setDetailtype(1L);
			account.setAccountmoney(asAccount.getMoney());
			account.setMoney(Math.abs(account.getMoney()));
			account.setDetaildatetime(new Date());
			asAccountdetailMapper.insertSelective(account);
		} catch (Exception e) {
			e.printStackTrace();
			return GPResult.build(200, "NO","操作失败");
		}
		return GPResult.ok();
	}

}
